<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="98px">
      <el-form-item label="传感器名称" prop="equName">
        <el-input v-model.trim="queryParams.equName" placeholder="请输入传感器名称" clearable style="width: 240px"
          @keyup.enter="handleQuery" @clear="handleQuery" @input="handleInput" />
      </el-form-item>
      <el-form-item label="通讯模组编码" prop="imei">
        <el-input v-model.trim="queryParams.imei" placeholder="请输入通讯模组编码" clearable style="width: 240px"
          @keyup.enter="handleQuery" @clear="handleQuery" @input="handleInput" />
      </el-form-item>
      <el-form-item label="在线状态" prop="ent_id" label-width="100px">
        <el-select v-model="queryParams.isOnline" clearable placeholder="请选择在线状态" @change="handleQuery"
          style="width: 240px">
          <el-option v-for="item in options0" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Upload" @click="handleImport">导入数据</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>
    <!-- 表格数据 -->
    <el-table v-loading="loading" size="large" :max-height="tableHeight" :data="dataList">
      <el-table-column type="index" label="序号" width="120" align="center">
        <template #default="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="传感器名称" v-if="columns[0].visible" prop="name" align="center" width="200" />
      <el-table-column label="通讯模组编码" v-if="columns[1].visible" align="center" width="200">
        <template #default="scope">
          <span :class="[scope.row.isOnline === 1?'online':'offline']">
            {{ scope.row.imei }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="通讯运营商" v-if="columns[2].visible" prop="isp" align="center" width="150" />
      <el-table-column label="物联网卡IMSI" v-if="columns[3].visible" prop="iccid" align="center" width="250" />
      <el-table-column label="电池电压(V)" v-if="columns[4].visible" prop="battery" align="center" width="120" />
      <el-table-column label="信号强度" v-if="columns[5].visible" prop="signal" align="center" width="100" />
      <el-table-column label="传感器状态" v-if="columns[6].visible" align="center" width="100">
        <template #default="scope">
          <span :class="[scope.row.state === 0?'online':'offline']">
            {{ scope.row.state==1?'未校准':scope.row.state==2?'断线':'正常' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="在线状态" v-if="columns[7].visible" align="center" width="100">
        <template #default="scope">
          <span :class="[scope.row.isOnline === 1?'online':'offline']">
            {{ scope.row.isOnline === 1 ? '在线' : '离线' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="绑定状态" v-if="columns[8].visible" align="center" width="100">
        <template #default="scope">
          <span :class="[scope.row.isLocked === 1?'online':'offline']">
            {{ scope.row.isLocked === 1 ? '已绑定' : '未绑定' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" min-width="240px" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Setting" @click="handleSys(scope.row)">传感器配置</el-button>
          <!-- <el-button link type="success" icon="Link" @click="handleUpdate(scope.row)">绑定位置</el-button> -->
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="roleRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属企业" prop="ent_id">
          <el-select v-model="form.ent_id" placeholder="请选择所属企业" @change="handleCascaderChange1">
            <el-option v-for="item in options1" :key="item.id" :label="item.companyName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门" prop="areaCode" v-if="form.ent_id">
          <el-cascader style="width: 600px;" ref="cascaderRef" @change="handleCascaderChange2" v-model="form.areaCode"
            :options="options2"
            :props="{ checkStrictly: true,children:'children',label:'partName',value:'partCode',emitPath:false}" />
        </el-form-item>
        <el-form-item label="传感器名称" prop="name">
          <el-input v-model.trim="form.name" maxlength="30" placeholder="请输入传感器名称" />
        </el-form-item>
        <el-form-item label="通讯编码" prop="imei">
          <el-input v-model.trim="form.imei" maxlength="30" placeholder="请输入通讯模组唯一编码" />
        </el-form-item>
        <el-form-item label="物联网卡号" prop="phone">
          <el-input v-model.trim="form.phone" maxlength="30" placeholder="请输入物联网卡号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title2" v-model="open2" width="900px" append-to-body :close-on-click-modal="false">
      <el-form ref="roleRef2" :model="form2" :rules="rules2" label-width="150px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="X轴振速关注阀值" prop="X_vV1">
              <el-input v-model.trim="form2.X_vV1" maxlength="30" placeholder="请输入X轴关注振速阀值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Y轴振速关注阀值" prop="Y_vV1">
              <el-input v-model.trim="form2.Y_vV1" maxlength="30" placeholder="请输入Y轴关注振速阀值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Z轴振速关注阀值" prop="Z_vV1">
              <el-input v-model.trim="form2.Z_vV1" maxlength="30" placeholder="请输入Z轴关注振速阀值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="X轴振速告警阀值" prop="X_vV2">
              <el-input v-model.trim="form2.X_vV2" maxlength="30" placeholder="请输入X轴振速告警阀值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Y轴振速告警阀值" prop="Y_vV2">
              <el-input v-model.trim="form2.Y_vV2" maxlength="30" placeholder="请输入Y轴振速告警阀值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Z轴振速告警阀值" prop="Z_vV2">
              <el-input v-model.trim="form2.Z_vV2" maxlength="30" placeholder="请输入Z轴振速告警阀值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="X轴振速危险阀值" prop="X_vV3">
              <el-input v-model.trim="form2.X_vV3" maxlength="30" placeholder="请输入X轴振速危险阀值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Y轴振速危险阀值" prop="Y_vV3">
              <el-input v-model.trim="form2.Y_vV3" maxlength="30" placeholder="请输入Y轴振速危险阀值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Z轴振速危险阀值" prop="Z_vV3">
              <el-input v-model.trim="form2.Z_vV3" maxlength="30" placeholder="请输入Z轴振速危险阀值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="X轴加速度关注阀值" prop="X_aV1">
              <el-input v-model.trim="form2.X_aV1" maxlength="30" placeholder="请输入X轴加速度关注阀值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Y轴加速度关注阀值" prop="Y_aV1">
              <el-input v-model.trim="form2.Y_aV1" maxlength="30" placeholder="请输入Y轴加速度关注阀值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Z轴加速度关注阀值" prop="Z_aV1">
              <el-input v-model.trim="form2.Z_aV1" maxlength="30" placeholder="请输入Z轴加速度关注阀值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="X轴加速度告警阀值" prop="X_aV2">
              <el-input v-model.trim="form2.X_aV2" maxlength="30" placeholder="请输入X轴加速度告警阀值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Y轴加速度告警阀值" prop="Y_aV2">
              <el-input v-model.trim="form2.Y_aV2" maxlength="30" placeholder="请输入Y轴加速度告警阀值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Z轴加速度告警阀值" prop="Z_aV2">
              <el-input v-model.trim="form2.Z_aV2" maxlength="30" placeholder="请输入Z轴加速度告警阀值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="X轴加速度危险阀值" prop="X_aV3">
              <el-input v-model.trim="form2.X_aV3" maxlength="30" placeholder="请输入X轴加速度危险阀值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Y轴加速度危险阀值" prop="Y_aV3">
              <el-input v-model.trim="form2.Y_aV3" maxlength="30" placeholder="请输入Y轴加速度危险阀值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Z轴加速度危险阀值" prop="Z_aV3">
              <el-input v-model.trim="form2.Z_aV3" maxlength="30" placeholder="请输入Z轴加速度危险阀值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="温度关注的阀值" prop="T_1">
              <el-input v-model.trim="form2.T_1" maxlength="30" placeholder="请输入温度关注的阀值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="温度告警的阀值" prop="T_2">
              <el-input v-model.trim="form2.T_2" maxlength="30" placeholder="请输入温度告警的阀值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="温度危险的阀值" prop="T_3">
              <el-input v-model.trim="form2.T_3" maxlength="30" placeholder="请输入温度危险的阀值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="信号告警值" prop="Signal">
              <el-input v-model.trim="form2.Signal" maxlength="30" placeholder="请输入信号告警值" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="电压告警值" prop="Battery">
              <el-input v-model.trim="form2.Battery" maxlength="30" placeholder="请输入电压告警值" />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="短包间隔时间" prop="p1">
              <el-input v-model.trim="form2.p1" maxlength="30" placeholder="请输入短包间隔时间" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="长包间隔时间" prop="p2">
              <el-input v-model.trim="form2.p2" maxlength="30" placeholder="请输入长包间隔时间" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" style="float: left;margin:0 0 10px 30px;" :disabled="disabled"
            @click="submitForm3">发送配置信息</el-button>
          <el-button type="primary" :disabled="disabled" @click="submitForm2">确 定</el-button>
          <el-button @click="open2=false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title3" v-model="open3" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="roleRef3" :model="form4" :rules="rules4" label-width="100px">
        <el-form-item label="所属部门" prop="areaCode">
          <el-input v-model.trim="form4.departID" maxlength="50" disabled placeholder="所属部门" />
        </el-form-item>
        <el-form-item label="传感器位置" prop="areaCode">
          <el-cascader style="width: 600px;" ref="cascaderRef4" v-model="form4.id" :options="options4"
            :props="cascaderProps4" @change="handleCascaderChange4">
            <!-- 自定义节点显示内容 -->
            <template #default="{ node, data }">
              <div class="cascader-node-content">
                <div class="node-info">
                  <span class="node-label">{{ data.label }}</span>
                </div>
                <!-- 使用数据中预设的标签信息 -->
                <el-tag :type="data.tagType || 'info'" size="small" class="cascader-tag">
                  {{ data.tagText || '未知' }}
                </el-tag>
              </div>
            </template>
          </el-cascader>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm3">确 定</el-button>
          <el-button @click="open3=false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="roleRef3" :model="form3" :rules="rules3" label-width="120px">
        <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
          :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
          :auto-upload="true" drag>
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" link style="float: left; margin: 0 0 10px 30px;" @click="handleDownloadTemplate">
            <el-icon>
              <Download />
            </el-icon>点击下载导入模板
          </el-button>
          <div>
            <el-button type="primary" @click="submitFileForm">确 定</el-button>
            <el-button @click="upload.open = false">取 消</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { getToken } from "@/utils/auth";
import { useInfoStore } from '@/store/modules/info.js'
const userInfo = useInfoStore();

const router = useRouter();
const { proxy } = getCurrentInstance();
// const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
const tableHeight = ref(document.documentElement.scrollHeight - 280 + "px");
import {  ElMessageBox, ElMessage, ElLoading } from 'element-plus'



const dataList = ref([]);
const open = ref(false);
const open2 = ref(false);
const open3 = ref(false);
const loading = ref(false);
const disabled = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const title2 = ref("");
const title3 = ref("");
const dateRange = ref([]);
const menuOptions = ref([]);
const deptOptions = ref([]);
const menuRef = ref(null);
const options0 = ref([
  { id: 1, name: '在线' },
  { id: 0, name: '离线' },
]);
const options1 = ref([]);
const options2 = ref([]); //部门
const options3 = ref([]); //线路列表
const cascaderRef = ref(null);
const options4 = ref([]);
const Dev_id = ref(null);
const tempRow = ref({});
const Sensers = ref(null);
// 列显隐信息
const columns = ref([
  { key: 1, label: `传感器名称`, visible: true },
  { key: 2, label: `通讯运营商`, visible: true },
  { key: 3, label: `物联网卡号`, visible: true },
  { key: 4, label: `Sim卡ICCID`, visible: true },
  { key: 5, label: `电池电压`, visible: true },
  { key: 6, label: `信号强度`, visible: true },
  { key: 7, label: '传感器状态', visible: true },
  { key: 8, label: '在线状态', visible: true },
  { key: 9, label: `绑定状态`, visible: true },
]);
const data = reactive({
  form: {
    id: null,
    ent_id: null,//企业ID
    imei: null,//通讯模组唯一编码
    name: null,//传感器名称
    isp	: null,//通讯运营商
    iccid: null,//Sim卡ICCID
    phone: null,//物联网卡号
    typeID: 1,//传感器型号:1为206
    photo:null,//传感器照片
    isLocked:0,//传感器是否锁定
    areaCode:null,//部门
    devcfg:null,//传感器配置信息Json串
  },
  form2: {
    id: null,
    X_vV1: null,
    Y_vV1: null,
    Z_vV1: null,
    X_vV2: null,
    Y_vV2: null,
    Z_vV2: null,
    X_vV3: null,
    Y_vV3: null,
    Z_vV3: null,
    X_aV1: null,
    Y_aV1: null,
    Z_aV1: null,
    X_aV2: null,
    Y_aV2: null,
    Z_aV2: null,
    X_aV3: null,
    Y_aV3: null,
    Z_aV3: null,
    T_1: null,
    T_2: null,
    T_3: null,
    Signal: null,
    Battery: null,
    p1:0,
    p2:0,
  },
  form3:{
    ent_id: null,//企业ID 
    station_id: null,//监测站点ID
  },
  form4:{
    departID: null,//部门id
    id: null,//位置id
  },
  queryParams: {
    pageNo: 1,
    pageSize: 10,
    imei: null,//传感器IMEI
    equName: null,//位置名称
    areaCode: null,//部门编码
    isOnline: null,//是否在线：1在线、0离线
    state: 1,//是否停用
  },
  rules: {
    ent_id: [{ required: true, message: "所属企业不能为空", trigger: "blur" }],
    areaCode: [{ required: true, message: "请选择部门", trigger: "blur" }],
    name: [{ required: true, message: "传感器名称不能为空", trigger: "blur" }],
    imei: [{ required: true, message: "通讯模组唯一编码不能为空", trigger: "blur" }],
  },
  rules2: {
    X_vV1: [{ required: true, message: "请输入", trigger: "blur" }],
    Y_vV1: [{ required: true, message: "请输入", trigger: "blur" }],
    Z_vV1: [{ required: true, message: "请输入", trigger: "blur" }],
    X_vV2: [{ required: true, message: "请输入", trigger: "blur" }],
    Y_vV2: [{ required: true, message: "请输入", trigger: "blur" }],
    Z_vV2: [{ required: true, message: "请输入", trigger: "blur" }],
    X_vV3: [{ required: true, message: "请输入", trigger: "blur" }],
    Y_vV3: [{ required: true, message: "请输入", trigger: "blur" }],
    Z_vV3: [{ required: true, message: "请输入", trigger: "blur" }],
    X_aV1: [{ required: true, message: "请输入", trigger: "blur" }],
    Y_aV1: [{ required: true, message: "请输入", trigger: "blur" }],
    Z_aV1: [{ required: true, message: "请输入", trigger: "blur" }],
    X_aV2: [{ required: true, message: "请输入", trigger: "blur" }],
    Y_aV2: [{ required: true, message: "请输入", trigger: "blur" }],
    Z_aV2: [{ required: true, message: "请输入", trigger: "blur" }],
    X_aV3: [{ required: true, message: "请输入", trigger: "blur" }],
    Y_aV3: [{ required: true, message: "请输入", trigger: "blur" }],
    Z_aV3: [{ required: true, message: "请输入", trigger: "blur" }],
    T_1: [{ required: true, message: "请输入", trigger: "blur" }],
    T_2: [{ required: true, message: "请输入", trigger: "blur" }],
    T_3: [{ required: true, message: "请输入", trigger: "blur" }],
    Signal: [{ required: true, message: "请输入", trigger: "blur" }],
    Battery: [{ required: true, message: "请输入", trigger: "blur" }],
    p1: [{ required: true, message: "请输入", trigger: "blur" }],
    p2: [{ required: true, message: "请输入", trigger: "blur" }],
  },
  rules3: {
    ent_id: [{ required: true, message: "请选择所属企业", trigger: "blur" }],
    station_id: [{ required: true, message: "请选择监测站", trigger: "blur" }],
  },
  rules4: {
    areaCode: [{ required: true, message: "请选择所属企业", trigger: "blur" }],
  },
});
// 数据预处理函数 - 统一不同层级的字段名
function normalizeOptions4Data(data, level = 0) {
  if (!Array.isArray(data)) return [];
  return data.map(item => {
    const normalizedItem = { ...item };
    // 添加层级信息，用于模板中判断
    normalizedItem.nodeLevel = level;

    // 根据层级设置统一的 label 字段和标签类型
    if (level === 0) {
      // 第一层：使用传感器名称相关字段
      normalizedItem.label = item.equName || item.deviceName || item.name || '未知传感器';
      normalizedItem.tagType = 'primary';
      normalizedItem.tagText = '传感器名称';
      // 第一层设置为禁用状态
      normalizedItem.disabled = true;
    } else {
      normalizedItem.label = item.poName || item.positionName || item.locationName || '未知位置';
      normalizedItem.tagType = 'success';
      normalizedItem.tagText = '传感器位置';
      normalizedItem.disabled = false;
    } 
    // 递归处理子节点
    if (item.position && Array.isArray(item.position)) {
      normalizedItem.position = normalizeOptions4Data(item.position, level + 1);
    }
    return normalizedItem;
  });
}

// Cascader 组件的 props 配置
const cascaderProps4 = ref({
  children: 'position',
  label: 'label',
  value: 'id',
  checkStrictly: true, // 启用严格模式，可以选择任意级别的选项
  emitPath: false, // 只返回选中节点的值，不返回完整路径
})
// 文件ID
const filedata = ref(null);
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/api/Device/AddDevicesStep1"
});

const { queryParams, form, form2, form3, form4, rules ,rules2 , rules3,rules4} = toRefs(data);

// 自定义校验函数
const validateTypeOrSpec = (rule, value, callback) => {
  if (!form.value.types && !form.value.specifications) {
    callback(new Error('型号和规格至少输入一项'));
  } else {
    callback();
  }
};
// 更新校验规则
rules.value.types = { validator: validateTypeOrSpec, trigger: 'blur' };
rules.value.specifications = { validator: validateTypeOrSpec, trigger: 'blur' };
// 跳转至传感器列表
function toList(form2) {
  router.push({
    path: "/cloudTv/device/sensorList",
    query: {
      dev_code: form2.dev_code,
    },
  });
}
/** 查询企业列表下拉 */
function getGetEnterpriseList() {
  proxy.cloudTv_API.GetListCom({}).then(response => {
    if (response.data) {
      options1.value = response.data || [];
      form.value.ent_id = form.value.ent_id?form.value.ent_id:options1.value[0].id;
      handleCascaderChange1();
    }else{
        proxy.$modal.msgWarning("还没有添加企业,请添加企业~");
      }
  });
}
 /** 查询部门列表下拉 */
function handleCascaderChange1() {
   proxy.cloudTv_API.GetListDepart({entID:form.value.ent_id}).then(response => {
      if(response.data?.length>0){
        options2.value = response.data;
        form.value.areaCode = form.value.areaCode?form.value.areaCode:options2.value[0].partCode;
      }else{
        options2.value = [];
        form.value.areaCode = null;
        proxy.$modal.msgWarning("当前企业还没有添加部门~");
      }
    });
}
// 主动关闭弹层
function handleCascaderChange2(e) {
    // 获取当前选中的节点列表
    const item = cascaderRef.value.getCheckedNodes()[0].data;
   // 获取当前选中的节点列表
    form.value.areaCode = item?.id;
    cascaderRef.value.togglePopperVisible(false)
}

// 处理传感器位置选择变化
function handleCascaderChange4(value) {
  console.log('选中的位置ID:', value);
  // 由于设置了 emitPath: false，这里的 value 就是选中节点的 id
  form4.value.id = value;
}
function handleEntChange2(value) {
  form.value.line_code = null;//选中监测站 清空支线
  form.value.line_id = null;
  getLineList(value);
}

/** 查询列表 */
function getList() {
  loading.value = true;
  proxy.cloudTv_API.GetPageListDev(queryParams.value).then(response => {
    dataList.value = response.data.list;
    total.value = response.data.total;
    loading.value = false;
  });
}
// 输入时触发的防抖处理函数
let timer = null;
function handleInput() {
  clearTimeout(timer);
  timer = setTimeout(handleQuery, 300);
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNo = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除传感器名称"' + row.name + '"的数据项?').then(function () {
    proxy.cloudTv_API.DelDev({
        id: row.id,
      }).then(response => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
      });
  })
}
  /** 导入按钮操作 */
  function handleImport() {
    upload.title = "导入文件信息";
    upload.open = true;
    // 清空文件数据
    filedata.value = null;
    // 清空上传组件中的文件
    const uploadRef = proxy.$refs["uploadRef"];
    if (uploadRef) {
      // 清空上传组件中的所有文件
      uploadRef.clearFiles(); 
    }
  };

  /** 下载模板操作 */
  function handleDownloadTemplate() {
    proxy.cloudTv_API.DownLoadTemplate({
    }).then(res => {
      const link = document.createElement('a');
      link.href = res.data;
      link.setAttribute('download', `导入传感器模版_${new Date().getTime()}.xls`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    });
  };

  /**文件上传中处理 */
  const handleFileUploadProgress = (event, file, fileList) => {
    upload.isUploading = true;
  };

  /** 文件上传成功处理 */
  const handleFileSuccess = (response, file, fileList) => {
    upload.isUploading = false;
    if (response.code == 1) {
      filedata.value = response.data;
     
    } else {
      proxy.$modal.msgError(response.message);
      proxy.$refs["uploadRef"].handleRemove(file);
    }
  };

  /** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["roleRef3"].validate(valid => {
    if (valid) {
      if (filedata.value) {
           proxy.cloudTv_API.AddDevicesStep2(filedata.value).then(res => {
            if(res.success && res.code==1){//成功
              proxy.$modal.msgSuccess(res.message);
              upload.open = false;
            } 
            if(!res.success && res.code==1){// 部分成功
              ElMessageBox.confirm(res.message, '系统提示', {  
                confirmButtonText: '继续添加',
                cancelButtonText: '取消添加',
                showClose:false,
                type: 'warning',
                customClass: 'custom-message-box' // 添加自定义类名
              }).then(() => {
                upload.open = false;
                proxy.cloudTv_API.AddDevicesStep3(res.data).then(res => {
                 upload.open = false;
                 proxy.$modal.msgSuccess(res.message);
                });
              }).catch(() => {
                proxy.cloudTv_API.AddDevicesStep4(res.data).then(res => {
                 upload.open = false;
                 proxy.$modal.msgSuccess(res.message);
                });
              });
            } 
           });
      } else {
        proxy.$modal.msgError("请等待文件上传完成");
      }
    }
  });
};

/** 重置新增的表单以及其他数据  */
function reset() {
  if (menuRef.value != undefined) {
    menuRef.value.setCheckedKeys([]);
  }
  form.value = {
    id: null,
    ent_id: null,//企业ID
    imei: null,//通讯模组唯一编码
    name: null,//传感器名称
    isp	: null,//通讯运营商
    iccid: null,//Sim卡ICCID
    phone: null,//物联网卡号
    typeID: 1,//传感器型号:1为206
    photo:null,//传感器照片
    isLocked:0,//传感器是否锁定
    areaCode:null,//部门
    devcfg:null,//传感器配置信息Json串
  };
}
/** 新增物料 */
function handleAdd() {
  reset();
  getGetEnterpriseList();
  open.value = true;
  title.value = "新增传感器";
}

/** 绑定位置 */
function handleUpdate(row) {
  // form4.value = {
  //   id: row.id,
  //   departID: row.areaName,
  //   areaCode: row.areaCode,
  // };
  proxy.cloudTv_API.GetListEqui({
    departID:1
  }).then(response => {
    if(response.data?.length>0){
      // 使用预处理函数统一字段名
      options4.value = normalizeOptions4Data(response.data);
      console.log('原始数据:', response.data);
      console.log('处理后数据:', options4.value);

    }else{
      options4.value = [];
      proxy.$modal.msgWarning("当前部门下还没有传感器~");
    }
  });
  let newRow = JSON.parse(JSON.stringify(row));
  open3.value = true;
  title3.value = row.name + " - 绑定位置";

}

// 传感器配置
function handleSys(row) {
  form2.value = JSON.parse(row.devcfg);
  form2.value.id = row.id;
  form2.value.p1 = form2.value.p1?form2.value.p1:10;
  form2.value.p2 = form2.value.p2?form2.value.p2:30;
  tempRow.value = row;
  open2.value = true;
  title2.value = row.name + " - 传感器配置";
}
  
/** 提交按钮 */
function submitForm() {
  proxy.$refs["roleRef"].validate(valid => {
    if (valid) {
      if (form.value.id) {
        proxy.cloudTv_API.UpdateDev({
          ...form.value,
        }).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        proxy.cloudTv_API.AddDevice({
          ...form.value,
        }).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 提交按钮 */
function submitForm2() {
  proxy.$refs["roleRef2"].validate(valid => {
    if (valid) {
      proxy.cloudTv_API.UpdateDev({
          ...tempRow.value,
          devcfg: JSON.stringify(form2.value),
      }).then(response => {
        proxy.$modal.msgSuccess("修改成功");
        // open2.value = false;
        getList();
      });
    }
  });
}
/** 发送配置信息给传感器 */
function submitForm3() {
  proxy.$refs["roleRef2"].validate(valid => {
    if (valid) {
      proxy.cloudTv_API.SendCfgSetting({
        id: form2.value.id,
        p1: form2.value.p1,
        p2: form2.value.p2,
        }).then(response => {
          proxy.$modal.msgSuccess("发送成功");
        });
    }
  });
  
}
// 复制
async function copy(text) {
  console.log(text);
  try {
    await navigator.clipboard.writeText(text);
    proxy.$modal.msgSuccess('复制成功');
  } catch (err) {
    console.log(err);

  }
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
getList();

</script>

<style lang="scss" scoped>
.el-input-number {
  width: 190px;
}

.required-star {
  color: #F56C6C;
  margin-right: 4px;
}

/* Cascader 自定义节点样式 */
.cascader-node-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  min-width: 200px;

  .node-info {
    display: flex;
    align-items: center;
    flex: 1;
    overflow: hidden;

    .node-icon {
      margin-right: 6px;
      font-size: 14px;
      color: #606266;
      flex-shrink: 0;
    }

    .node-label {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

  .cascader-tag {
    flex-shrink: 0;
    margin-left: 8px;
    font-size: 10px;
    height: 18px;
    line-height: 16px;
    border-radius: 9px;
    padding: 0 6px;
    font-weight: 500;
  }
}

/* 禁用状态的节点样式 */
:deep(.el-cascader-node.is-disabled) {
  .cascader-node-content {
    opacity: 0.6;

    .node-label {
      color: #c0c4cc;
    }

    .cascader-tag {
      opacity: 0.7;
      background-color: #f5f7fa !important;
      border-color: #e4e7ed !important;
      color: #909399 !important;
    }
  }
}
.online {
  color: #67C23A;
}

.offline {
  color: #F56C6C;
}
/* 不同类型标签的自定义样式 */
:deep(.el-tag--primary.cascader-tag) {
  background-color: #ecf5ff;
  border-color: #b3d8ff;
  color: #409eff;
}

:deep(.el-tag--success.cascader-tag) {
  background-color: #f0f9ff;
  border-color: #95de64;
  color: #52c41a;
}

:deep(.el-tag--warning.cascader-tag) {
  background-color: #fdf6ec;
  border-color: #f7ba2a;
  color: #fa8c16;
}

:deep(.el-tag--info.cascader-tag) {
  background-color: #f4f4f5;
  border-color: #d3d4d6;
  color: #909399;
}
</style>

<style lang="scss">
/* 自定义 MessageBox 样式 */
.custom-message-box {
  /* 可以根据实际的 el-dialog 高度来调整 top 值 */
  top: -250px; 
  transform: none; 
}
</style>